// pages/user-subscribe/index.js
const app = getApp();

Page({
  data: {
    records: [],      // 预约记录列表
    loading: true,    // 加载状态
    hasMore: true,    // 是否还有更多数据
    pageSize: 10,     // 每页数量
    currentPage: 0    // 当前页码
  },

  onLoad() {
    this.loadData();
  },

  // 加载数据
  async loadData() {
    try {
      this.setData({ loading: true });
      
      const { result } = await wx.cloud.callFunction({
        name: 'getUserOpenid'
      });
      
      const db = wx.cloud.database();
      const res = await db.collection('formData')
        .where({
          _openid: result.openid
        })
        .orderBy('createdAt', 'desc')
        .limit(this.data.pageSize)
        .skip(this.data.currentPage * this.data.pageSize)
        .get();
      
      // 格式化数据
      const formattedData = res.data.map(item => ({
        ...item,
        formattedTime: this.formatTime(item.createdAt),
        formattedStatus: this.formatStatus(item.status)
      }));
      
      this.setData({
        records: this.data.currentPage === 0 
          ? formattedData 
          : [...this.data.records, ...formattedData],
        loading: false,
        hasMore: res.data.length === this.data.pageSize,
      });
      
    } catch (err) {
      console.error('加载数据失败:', err);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
      this.setData({ loading: false });
    }
  },

  // 刷新数据
  refreshData() {
    this.setData({ currentPage: 0 });
    this.loadData();
  },

  // 加载更多数据
  loadMoreData() {
    if (!this.data.hasMore) return;
    
    this.setData({ currentPage: this.data.currentPage + 1 });
    this.loadData();
  },

  // 取消预约
  async cancelRecord(e) {
    const id = e.currentTarget.dataset.id;
    
    try {
      wx.showLoading({ title: '处理中...' });
      
      // 调用云函数更新状态
      const res = await wx.cloud.callFunction({
        name: 'userSubscribe',
        data: {
          action: 'updateStatus',
          id: id,
          status: 'cancelled'
        }
      });
      
      if (res.result.success) {
        wx.showToast({ title: '已取消预约', icon: 'success' });
        // 刷新列表
        this.refreshData();
      }
    } catch (err) {
      console.error('取消预约失败:', err);
      wx.showToast({ title: '操作失败', icon: 'none' });
    } finally {
      wx.hideLoading();
    }
  },

  // 格式化状态显示
  formatStatus(status) {
    const statusMap = {
      pending: '待确认',
      approved: '已通过',
      rejected: '已拒绝',
      cancelled: '已取消'
    };
    return statusMap[status] || status;
  },

  // 格式化时间显示
  formatTime(date) {
    const d = new Date(date)
    const year = d.getFullYear()
    const month = d.getMonth() + 1
    const day = d.getDate()
    const hour = d.getHours()
    const minute = d.getMinutes()
    
    return `${year}-${month}-${day} ${hour}:${minute}`
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.loadMoreData();
  }
});